package com.blast.cn.http

import android.content.Context
import android.text.TextUtils
import com.alibaba.fastjson.JSONObject
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.HttpParams
import com.lzy.okgo.model.Response
import com.wxl.common.AppConstant
import com.wxl.common.AppContext
import com.wxl.common.bean.AppInfoBean
import com.wxl.common.bean.DetonatorInfoBean
import com.wxl.common.http.OkGoApi
import com.wxl.common.http.SerialHttpCallback
import com.wxl.common.room.entity.BlastRecordEntity
import com.wxl.common.room.entity.UserEntity
import com.wxl.common.util.DeviceUtil
import com.wxl.common.util.EncryptUtils
import com.wxl.common.util.StringUtils
import com.wxl.common.util.Toll

class MainHttps {

    companion object {

        /***
         * 上传起爆器信息
         */
        fun loadupDetonatorInfo(
            mac: String,
            iem: String,
            callback: SerialHttpCallback<DetonatorInfoBean>
        ) {
            val params = HttpParams()
            params.put("action", AppConstant.ACTION_UPLOAD_DETONATOR_INFO)
            params.put("mac", mac)
            params.put("IEM", iem)
            OkGoApi.api
                .get()
                .params(params)
                .execute(callback)
        }


        /**
         * 检查app升级信息
         */
        fun checkAppUpdate(context: Context, callback: SerialHttpCallback<AppInfoBean>) {
            val versionName = DeviceUtil.getVersionName(context)
            val param = HttpParams()
            param.put("action", "getAppInfo")
            param.put("appversion", versionName)
            OkGoApi.api.get().params(param).execute(callback)
        }


        /**
         * 登陆
         */
        fun login(name: String, pwd: String, callback: SerialHttpCallback<UserEntity>) {
            val param = HttpParams()
            param.put("action", "getUserInfo")
            param.put("idcode", name)
            param.put("userpass", StringUtils.string2MD5(pwd))
            param.put(
                "appversion",
                DeviceUtil.getVersionName(AppContext.appContext.getApplication())
            )
            OkGoApi.api.get().params(param).execute(callback)
        }


        /**
         * 上传爆破日志
         */
        fun uploadBlastRecord(item: BlastRecordEntity,callback:OnUploadBlastCallback,isToast:Boolean) {
            item.action = "postBpRecord"
            OkGo.post<String>(AppConstant.baseIndexUrl + "api/bpRecordServlet")
                .upJson(JSONObject.toJSONString(item))
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {

                    }

                    override fun onError(response: Response<String>?) {

                    }

                    override fun onFinish() {
                        uploadBlastInfo(item,callback,isToast)
                    }
                })
        }


        /**
         * 上传爆破信息，民爆服务器
         */
       private fun uploadBlastInfo(item: BlastRecordEntity,callback:OnUploadBlastCallback,isToast:Boolean) {
            val uids = arrayListOf<String>()
            if (item.list != null && item.list.isNotEmpty()) {
                item.list.forEach {
                    uids.add(it.UID)
                }
            }
            if (uids.isEmpty()) {
                uids.add("6100101D99903")
                uids.add("6100101D99889")
                uids.add("6100101D99850")
            }

            var map = HashMap<String, String>()
            map.put("sbbh", "F90000000000")
            map.put("jd", AppContext.appContext.getLon().toString())
            map.put("wd", AppContext.appContext.getLat().toString())
            map.put("bpsj", item.blastTime)
            if (!TextUtils.isEmpty(AppContext.appContext.getLoginAccount())) {
                map.put("bprysfz", AppContext.appContext.getLoginAccount())
            } else {
                map.put("bprysfz", "441881199505017218")
            }
            var uid = StringBuffer()
            uids.forEach {
                uid.append(it).append(",")
            }
            uid.deleteCharAt(uid.length - 1)
            map.put("uid", uid.toString())
            if(AppContext.appContext.getAuthDmInfo() != null){
                map.put("xmbh",AppContext.appContext.getAuthDmInfo()!!.projectnumber)
                map.put("htid",AppContext.appContext.getAuthDmInfo()!!.contractid)
            } else {
                map.put("xmbh","370100X15040025")
                map.put("htid","370101318060004")
            }

            if(!TextUtils.isEmpty(AppContext.appContext.getBlastDwmc())){
                map.put("dwmc",AppContext.appContext.getBlastDwmc())
            } else {
                map.put("dwmc","济南黄河爆破工程有限责任公司")
            }
            if(!TextUtils.isEmpty(AppContext.appContext.getBlastDwCode())){
                map.put("dwdm",AppContext.appContext.getBlastDwCode())
            } else {
                map.put("dwdm","3701004200003")
            }

            val data = EncryptUtils.endocdeNoURL(JSONObject.toJSONString(map),EncryptUtils.mbolsk)
            val param = HttpParams()
            param.put("param",data)
            val postRequest = OkGo.post<String>(AppConstant.mbBaseUrl+"DzlgSysbJsonServlert")
            postRequest.params(param)
            postRequest.execute(object : StringCallback(){
                override fun onSuccess(response: Response<String>?) {
                    if(response != null && response.isSuccessful && response.body() != null
                        && !TextUtils.isEmpty(response.body())){
                        val jsonObject = JSONObject.parseObject(response.body())
                        if(jsonObject != null && jsonObject.containsKey("success") && jsonObject.getString("success") != null
                            && TextUtils.equals("fail",jsonObject.getString("success"))){
                            val e = jsonObject.getString("cwxx")
                            if(isToast) {
                                Toll.toll(qblogError(e))
                            }
                            callback.onUploadBlast(false)
                        } else {
                            callback.onUploadBlast(true)
                        }
                    } else {
                        callback.onUploadBlast(true)
                    }
                }

                override fun onError(response: Response<String>?) {
                    if(isToast) {
                        Toll.toll("上传失败")
                    }
                    callback.onUploadBlast(false)
                }
            })
        }

      private  fun qblogError(errorCode: String?): String {
            var msg = "未知错误"
            when (errorCode) {
                "1" -> msg = "非法的申请信息"
                "2" -> msg = "起爆器未备案或未设置作业任务"
            }
            return msg
        }


        /**
         * 修改密码
         */
        fun updatePwd(pwd:String,callback:SerialHttpCallback<String>){
            val param = HttpParams()
            val p = StringUtils.string2MD5(pwd)
            param.put("action","changePsw")
            param.put("userpass",p)
            param.put("idcode",AppContext.appContext.getLoginAcc()!!.idcode)
            OkGoApi.api.post()
                .params(param)
                .execute(callback)
        }

        /**
         * 上传采集器信息
         */
        fun uploadCollectorInfo(title:String,version:String,callback:SerialHttpCallback<String>){
            val param = HttpParams()
            param.put("title",title)
            param.put("version",version)
            param.put("status","003001")
            OkGoApi.api.post()
                .params(param)
                .execute(callback)
        }

    }

}